//
//  OAuthViewController.swift
//  Swift微博
//
//  Created by adel on 2017/8/22.
//  Copyright © 2017年 com.bailun91. All rights reserved.
//

import UIKit
import SVProgressHUD
class OAuthViewController: UIViewController {
    
    @IBOutlet weak var webView: UIWebView!

    
    override func viewDidLoad() {
        super.viewDidLoad()
    
        setupNav()
        
        loadPage()
    }
}


//UI设置
extension OAuthViewController{
    
    //设置Nav
   fileprivate func setupNav() {
        
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: .plain, target: self, action: #selector(OAuthViewController.closeItemClick))
        
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "填充", style: .plain, target: self, action: #selector(OAuthViewController.fillItemClick))
        
        title = "登录页面"
    }
    
    
    //加载网页
  fileprivate  func loadPage(){
    // 1.获取登录页面的URLString
    let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(app_key)&redirect_uri=\(redirect_uri)"
    
    // 2.创建URL
    guard let url = URL(string: urlString) else {
        return
    }
    
    // 3.创建request
    
    let request = URLRequest(url: url)
    
    // 4. 加载request对象
    webView.loadRequest(request)
    
    }
}

// MARK:按钮的点击
extension OAuthViewController{
 
    //填充按钮
   @objc fileprivate func fillItemClick() {
    
    let jsCode = "document.getElementById('userId').value='18821908860';document.getElementById('passwd').value='bailuaicy3344';"
    
    // 2.执行js代码
    webView.stringByEvaluatingJavaScript(from: jsCode)
    
    }
    
   @objc fileprivate func closeItemClick() {
        dismiss(animated: true, completion: nil)
    }
    
}




// MARK:- UIWebViewDelegate
extension OAuthViewController:UIWebViewDelegate{

    // 开始加载网页
    func webViewDidStartLoad(_ webView: UIWebView) {
        SVProgressHUD.show()
    }
    
    //已经加载网页
    func webViewDidFinishLoad(_ webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    
    //加载网页失败
    func webView(_ webView: UIWebView, didFailLoadWithError error: Error) {
        SVProgressHUD.dismiss()
    }
    
    // 当准备加载某一个页面时,会执行该方法
    // 返回值: true -> 继续加载该页面 false -> 不会加载该页面
    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        // 1.获取加载网页的NSURL
        guard let url = request.url else {
            return true
        }
        
        // 2.获取url中的字符串
        let urlString = url.absoluteString
        
        
        // 3.判断该字符串中是否包含code
        guard urlString.contains("code=") else {
            return true
        }
        
        // 4.将code截取出来
        let code = urlString.components(separatedBy: "code=").last!
       
        // 5.请求accessToken
        loadAccessToken(code:code)
        
        return true
    }
}


extension OAuthViewController{
    // MARK:- 请求AccessToken
    func loadAccessToken(code : String) {
        NETWorkTool.sharedNETWorkTool.loadAccessToken(code: code) { (result, error) in
            
            // 1.错误校验
            if error != nil {
                print(error!)
                return
            }
            
            // 2.拿到结果
            guard let accountDict = result else {
                print("没有获取授权后的数据")
                return
            }
            SVProgressHUD.dismiss()
            // 3.将字典转成模型对象
            let account = UserAccount(dic: accountDict)

            // 4.请求用户信息
            self.loadUserInfo(account: account)
        }
    }
    
    
    // MARK:- 请求用户信息
    func loadUserInfo(account : UserAccount) {
        // 1.获取AccessToken
        guard let accessToken = account.access_token else {
            return
        }
        
        // 2.获取uid
        guard let uid = account.uid else {
            return
        }
        
        // 3.发送网络请求
        
        NETWorkTool.sharedNETWorkTool.loadUserInfo(access_token: accessToken, uid: uid) { (result, error) in
            
            // 1.错误校验
            if error != nil {
                print(error!)
                return
            }
            
            // 2.拿到用户信息的结果
            guard let userInfoDict = result else {
                return
            }
            
            // 3.从字典中取出昵称和用户头像地址
            account.screen_name = userInfoDict["screen_name"] as? String
            account.avatar_large = userInfoDict["avatar_large"] as? String
            
            
            // 4.2.保存对象
            NSKeyedArchiver.archiveRootObject(account, toFile: UserAccountViewModel.sharedUserAccountViewModel.accountPath)
            
            // 5.显示欢迎界面
            
            // 5.1给单例对象的account 赋值
            UserAccountViewModel.sharedUserAccountViewModel.account = account
        
            // 5.2显示界面
            self.dismiss(animated: false, completion: {
                UIApplication.shared.keyWindow?.rootViewController = WelcomeVC()
            })
        }
        
        }
}
